package com.quan.sport.gateway.filter;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import com.alibaba.fastjson.JSON;
import com.quan.common.base.bean.ResultBean;
import com.quan.common.utils.JwtTokenUtils;
import com.quan.common.utils.RedisOperator;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;

//@Component
public class ValidateTokenFilter/* extends OncePerRequestFilter*/ {

	/*private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private RedisOperator redisOperator;

	*//**
	 * JwtToken秘钥
	 *//*
	@Value("${jwt.secret:123456}")
	private String jwtSecret;

	*//**
	 * JwtToken过去时间（秒）
	 *//*
	@Value("${jwt.timeout:1800}")
	private Long timeout;
	
	*//**
	 * 不需要拦截的URI请求
	 *//*
	private static final String excludes = "((login$)|(/login))";
	
	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
		if(!requestIsExclude(request)) {
			if(!validToken(request)) {
				response.setStatus(200);
				response.setCharacterEncoding("UTF-8");
		        response.setContentType("application/json; charset=utf-8");
		        ServletOutputStream out = response.getOutputStream();
		        
		        ResultBean loginTimeOut = ResultBean.loginTimeOut();
		        String message = JSON.toJSONString(loginTimeOut);
		        out.write(message.getBytes("utf-8"));
		        IOUtils.closeQuietly(out);
		        //out.flush();
		        logger.debug("状态：{}，消息：{}", loginTimeOut.getStatus(), loginTimeOut.getMsg());
			}
		}
		filterChain.doFilter(request, response);
	}
	
	public boolean validToken(HttpServletRequest request) {
		String token = request.getHeader("Auth-Token");
		
		// Token为空
		if (null == token || "".equals(token.trim())) {
			return false;
		}
		
		Jws<Claims> parse = JwtTokenUtils.parse(token, jwtSecret);
		if (null != parse) {
			Claims body = parse.getBody();
			
			return this.redisOperator.hasKey("sso:token:" + body.get("userId"));
		} else {
			logger.info("Token解析失败");
			return false;
		}
	}
	
	private boolean requestIsExclude(HttpServletRequest request) {
		// 没有设定excludes是，所有经过filter的请求都需要被处理
		if (null == excludes || "".equals(excludes.trim())) {
			return false;
		}

		// 获取去除context path后的请求路径
		String contextPath = request.getContextPath();
		String uri = request.getRequestURI();
		uri = uri.substring(contextPath.length());

		Pattern p = Pattern.compile(excludes);
		Matcher m = p.matcher(uri);
		// 正则表达式匹配URI被排除，不需要拦截
		boolean isExcluded = m.find();
		if (isExcluded) {
			logger.debug("该请求地址不需验证Token: {}", uri);
		}
		return isExcluded;
	}*/

}
